package com.cash.loan.modular.cash.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cash.loan.core.upload.QiniuService;
import com.cash.loan.modular.cash.dao.LoanCateMapper;
import com.cash.loan.modular.cash.dao.LoanCateProductMapper;
import com.cash.loan.modular.cash.model.LoanCate;
import com.cash.loan.modular.cash.service.CateService;
import com.cash.loan.modular.cash.transfer.CateDto;
import com.cash.loan.modular.cash.transfer.UpdateCateDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Administrator
 * @Date 2018-09-29 16:15
 */
@Service
public class CateServiceImpl implements CateService {

    @Autowired
    private LoanCateMapper cateMapper;

    @Autowired
    private LoanCateProductMapper cateProductMapper;

    @Autowired
    private QiniuService qiniuService;

    @Override
    public List<LoanCate> list() {
        List<LoanCate> loanCateList = cateMapper.selectList(new EntityWrapper<LoanCate>());
        loanCateList.stream().forEach(cate -> {
            cate.setIconPath(qiniuService.getUrl(cate.getIconPath()));
        });
        return loanCateList;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean add(CateDto cateDto) {
        LoanCate loanCate = new LoanCate();
        BeanUtils.copyProperties(cateDto,loanCate);
        loanCate.setIconPath(qiniuService.getUri(loanCate.getIconPath()));
        Integer result = cateMapper.insert(loanCate);
        if(result != 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public LoanCate detail(Integer id) {
        LoanCate loanCate = cateMapper.selectById(id);
        loanCate.setIconPath(qiniuService.getUrl(loanCate.getIconPath()));
        return loanCate;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean update(UpdateCateDto cateDto) {
        LoanCate loanCate = new LoanCate();
        BeanUtils.copyProperties(cateDto,loanCate);
        loanCate.setIconPath(qiniuService.getUri(loanCate.getIconPath()));
        Integer result = cateMapper.updateById(loanCate);
        if(result != 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean delete(Integer id) {
        cateProductMapper.deleteByCateId(id);
        cateMapper.deleteById(id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean bindCateAndProduct(Integer productId, List<Integer> cateIdList) {
        cateProductMapper.deleteByProductId(productId);
        cateProductMapper.batchInsert(productId,cateIdList);
        return true;
    }
}
